<template>
    <div class="full post-page mavon-style">
        <mavon-editor ref="editorRef" v-loading="loading.article" class="article-editor" codeStyle='github' v-model="form.content" :font-size='"18px"' :toolbars="toolbars" @imgAdd="addImg" @imgDel="delImg" placeholder="✍ 开始你的创作吧~"/>
        <div class="float-button" @click="dialShowing=true"><i class="icon-ios-checkmark"></i></div>
        <el-dialog width="1000px" :visible.sync="dialShowing" :show-close="false">
            <div slot="title" style="display: none;"></div>
            <div class="modal-box">
                <div class="desc-panel">
                    <picture-input
                            @change="picChange" hideChangeButton plain title="点击或拖拽，更换文章封面"></picture-input>
                    <div class="upload-img-info">
                        点击或拖拽，上传文章封面
                    </div>
                </div>
                <div class="form-panel">
                    <div class="form-header">文章信息</div>
                    <el-form class="form-style" :model="form">
                        <el-form-item>
                            <el-input class="input-title" placeholder="文章标题" v-model="form.title"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-input type="textarea" placeholder="摘要" v-model="form.summary" maxlength="250"
                                      resize="none" :autosize="{ minRows: 5, maxRows: 6 }" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-tag v-if="tag.selected" :key="index" v-for="(tag, index) in tags"
                                    :disable-transitions="false" :effect="tag.selected ? 'dark' : 'plain'" size="medium"
                                    @click="tagClicked(tag)" class="post-tag">{{ tag.tagName }}
                            </el-tag>
                            <el-popover class="tag-popover" placement="bottom" width="400" trigger="click"
                                        popper-class="tag-popover-popper">
                                <div class="tags-box">
                                    <el-scrollbar>
                                        <el-tag :key="index" v-for="(tag, index) in tags" :disable-transitions="false"
                                                :effect="tag.selected ? 'dark' : 'plain'" size="medium"
                                                @click="tagClicked(tag)" class="post-tag" :title="tag.tagName">{{
                                            tag.tagName }}
                                        </el-tag>
                                        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue"
                                                  ref="saveTagInput" size="small"
                                                  @keyup.enter.native="handleInputConfirm"
                                                  @blur="handleInputConfirm"></el-input>
                                        <el-button v-else class="button-new-tag" size="swebpack.dev.conf.jsmall"
                                                   @click="showInput">+ 添加标签
                                        </el-button>
                                    </el-scrollbar>
                                </div>
                                <el-button slot="reference" type="primary" size="mini" class="tag-popover-btn"
                                           icon="el-icon-collection-tag" plain>标签
                                </el-button>
                            </el-popover>
                        </el-form-item>
                        <el-button type="primary" @click="save" :loading="loading.global" round>点击发布</el-button>
                    </el-form>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
	saveArticle,
	getTags,
	getArticle
} from '../../../../service/postService';
import { uploadImg } from '../../../../service/imgService';
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import DateUtil from '../../../../../utils/date.js';
import Util from '../../../../../utils/util.js';
import PictureInput from 'vue-picture-input';

export default {
	name: 'post-page',
	data () {
		return {
			dialShowing: false,
			loading: {
				global: false,
				article: false
			},
			form: {
				title: '',
				summary: '',
				content: '',
				tag: [],
				coverImg: ''
			},
			tags: [],
			inputVisible: false,
			inputValue: '',
			timeTaskId: '',
			toolbars: {
				bold: true, // 粗体
				italic: true, // 斜体
				header: true, // 标题
				underline: true, // 下划线
				strikethrough: true, // 中划线
				mark: true, // 标记
				superscript: true, // 上角标
				subscript: true, // 下角标
				quote: true, // 引用
				ol: true, // 有序列表
				ul: true, // 无序列表
				link: true, // 链接
				imagelink: true, // 图片链接
				code: true, // code
				table: true, // 表格
				fullscreen: true, // 全屏编辑
				readmodel: true, // 沉浸式阅读
				htmlcode: true, // 展示html源码
				help: true, // 帮助
				/* 1.3.5 */
				undo: true, // 上一步
				redo: true, // 下一步
				trash: true, // 清空
				/* 1.4.2 */
				navigation: true, // 导航目录
				/* 2.1.8 */
				alignleft: true, // 左对齐
				aligncenter: true, // 居中
				alignright: true, // 右对齐
				/* 2.2.1 */
				subfield: true, // 单双栏模式
				preview: true // 预览
			},
			imgUrlConvertMap: {}
		};
	},
	components: {
		mavonEditor,
		PictureInput
	},
	mounted () {
		let self = this;

		if (this.$route.params.id) {
			let editorParams = {
				id: this.$route.params.id.split('=')[1]
			};
			self.loading.article = true;
			getArticle(editorParams)
				.then(data => {
					self.loading.article = false;
					let article = data.result;
					self.form.title = article.title;
					self.form.summary = article.summary;
					self.form.tag = article.tags.split(',');
					self.form.content = article.content;
				})
				.catch(e => {
					self.loading.article = false;
				});
		} else {
			if (sessionStorage.getItem('title')) {
				self.form.title = sessionStorage.getItem('title');
			}
			if (sessionStorage.getItem('article')) {
				self.form.content = sessionStorage.getItem('article');
			}
			if (sessionStorage.getItem('summary')) {
				self.form.summary = sessionStorage.getItem('summary');
			}
			self.timeTaskId = window.setInterval(() => {
				if (self.form.content && self.form.content != '') {
					sessionStorage.setItem('article', self.form.content);
					sessionStorage.setItem('title', self.form.title);
					sessionStorage.setItem('summary', self.form.summary);
				}
			}, 100);
		}
		let params = {};
		getTags(params).then(data => {
			data.resultList.forEach(tag => {
				let item = {
					tagName: tag,
					selected: Util.arrayContains(self.form.tag, tag)
				};
				self.tags.push(item);
			});
		});
	},
	destroyed () {
		window.clearInterval(this.timeTaskId);
	},
	methods: {
		save () {
			let self = this;
			let postTags = '';
			this.tags.forEach(tag => {
				if (tag.selected) {
					postTags += tag.tagName + ',';
				}
			});
			if (!this.form.title || this.form.title == '') {
				return;
			}
			let params = {
				id: this.$route.params.id
					? this.$route.params.id.split('=')[1]
					: '',
				title: this.form.title,
				content: Util.imgUrlRectifyFallback(this.form.content),
				summary: this.form.summary,
				coverImg: this.form.coverImg,
				tags: postTags.substr(0, postTags.length - 1),
				date: DateUtil.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
			};
			self.loading.global = true;
			saveArticle(params)
				.then(data => {
					if (data.status === 200) {
						self.$message.success('保存成功');
						self.loading.global = false;
						self.dialShowing = false;
					} else {
						self.$notify.error('服务器内部异常: ' + data.message);
					}
				})
				.catch(e => {
					self.$message.error('页面出错: ' + e.message);
				})
				.finally(() => {
					self.loading.global = false;
				});
		},
		tagClicked (tag) {
			if (!tag.selected) {
				if (this.form.tag.length < 4) {
					this.form.tag.push(tag.name);
				} else {
					this.$message('超出最大标签选择（不超过4个）');
					return;
				}
			} else {
				this.form.tag.splice(this.form.tag.indexOf(tag.name));
			}
			tag.selected = !tag.selected;
		},
		showInput () {
			this.inputVisible = true;
			this.$nextTick(_ => {
				this.$refs.saveTagInput.$refs.input.focus();
			});
		},
		handleInputConfirm () {
			let inputValue = this.inputValue;
			if (inputValue) {
				let tag = {
					tagName: inputValue,
					selected: true
				};
				this.tags.push(tag);
			}
			this.inputVisible = false;
			this.inputValue = '';
		},
		addImg (pos, file) {
			let params = {
				imgOfBase64: file.miniurl,
				alias: `《${this.form.title}》内容-${pos}`,
				associateAttribute: `文章内容:《${this.form.title}》`
			};
			uploadImg(params)
				.then(data => {
					let rectifyUrl = Util.imgUrlRectify(data.url);
					this.imgUrlConvertMap[rectifyUrl] = data.url;
					this.$refs['editorRef'].$img2Url(pos, rectifyUrl);
				})
				.catch(e => {
					console.error(e);
					this.$message.error('上传图片失败!');
				});
		},
		delImg (pos) {
			console.log(pos);
		},
		picChange (image) {
			this.form.coverImg = image;
		}
	}
};
</script>

<style lang="scss" scoped>
.post-page {
	height: 100%;
	padding: 10px;

	.float-button {
		position: absolute;
		bottom: 50px;
		right: 50px;
		width: 60px;
		height: 60px;
		border-radius: 50%;
		background: #1a48cb;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);

		&:hover {
			background: #5d82ed;
		}

		&:active {
			background: #1a48cb;
		}

		i {
			font-size: 48px;
			color: white;
			font-weight: bold;
		}
	}

	.modal-box {
		height: 420px;

		.form-panel {
			float: left;
			width: calc(100% - 420px);
			height: 100%;

			.form-header {
				height: 80px;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 20px;
			}

			.form-style {
				padding: 0px 40px;

				.post-tag {
					cursor: pointer;
					margin-right: 5px;
					margin-bottom: 5px;

					&.selected {
						background: #409eff;
						color: white;
					}
				}
			}
		}

		.desc-panel {
			float: left;
			width: 420px;
			height: 100%;
			position: relative;

			.upload-img-info {
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				margin: 20px;
				border: 1px dashed #30049c;
				height: calc(100% - 40px);
				width: calc(100% - 40px);
				top: 0;
			}
		}
	}

	.custom-toolbar {
		height: 60px;
		line-height: 60px;
		width: 100%;

		.title-box {
			padding: 0 10px;

			.input-title {
				float: left;
				width: 400px;
			}

			.tag-popover {
				height: 100%;
				display: flex;
				align-items: center;

				.tag-popover-btn {
					float: left;
					margin-left: 10px;
				}
			}
		}
	}

	.article-editor {
		height: 100%;
	}
}
</style>

<style lang="scss">
.tag-popover-popper {
	.tags-box {
		height: 400px;
		overflow: auto;

		.post-tag {
			cursor: pointer;
			margin: 0 5px 5px;
			width: 80px;
			text-align: center;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;

			&.selected {
				background: #409eff;
				color: white;
			}
		}

		.button-new-tag {
			margin-right: 10px;
			height: 32px;
			line-height: 30px;
			padding-top: 0;
			padding-bottom: 0;
		}

		.input-new-tag {
			width: auto;
			margin-right: 10px;
			vertical-align: bottom;
		}
	}
}
</style>
